/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import java.awt.Desktop;
import java.io.*;
import java.net.MalformedURLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import javax.swing.SwingWorker;

/**
 *
 * @author TommySprat
 */
public class MainJFrame extends javax.swing.JFrame {

    String url;
    File temp;

    enum downloadState {

        READY, DOWNLOADING, DONE
    }
    private static downloadState currentDownloadState = downloadState.READY;

    /**
     * Creates new form MainJFrame
     */
    public MainJFrame() {
        initComponents();
        initTempFile();
        //Vraag naar de URl van het te downloaden bestand
        url = JOptionPane.showInputDialog("Geef de URL op voor de download.");
        lbURL.setText(url);
    }

    /**
     * Creëert een tijdelijk bestand waarnaar je kan shrijven
     */
    public void initTempFile() {
        try {
            temp = File.createTempFile("OOP", ".temp");
            lbDownloadLocation.setText(temp.getName());
        } catch (IOException e) {
            System.out.println(e);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btStart = new javax.swing.JButton();
        btOpenFolder = new javax.swing.JButton();
        lbBezigMetDownloaden = new javax.swing.JLabel();
        lbURL = new javax.swing.JLabel();
        lbDownloadnaar = new javax.swing.JLabel();
        lbOverdrachtsnelheid = new javax.swing.JLabel();
        lbETA = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();
        lbDownloadLocation = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btStart.setText("Start");
        btStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btStartActionPerformed(evt);
            }
        });

        btOpenFolder.setText("Map openen");
        btOpenFolder.setEnabled(false);
        btOpenFolder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btOpenFolderActionPerformed(evt);
            }
        });

        lbBezigMetDownloaden.setText("Bezig met downloaden:");

        lbURL.setText("http://");

        lbDownloadnaar.setText("Downloaden naar:");

        lbOverdrachtsnelheid.setText("Overdrachtsnelheid:");

        lbETA.setText("Resterende tijd circa:");

        lbDownloadLocation.setText("jLabel1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(progressBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 226, Short.MAX_VALUE)
                        .addComponent(btOpenFolder)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btStart))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(lbURL))
                            .addComponent(lbBezigMetDownloaden)
                            .addComponent(lbOverdrachtsnelheid)
                            .addComponent(lbETA)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lbDownloadnaar)
                                .addGap(26, 26, 26)
                                .addComponent(lbDownloadLocation)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbBezigMetDownloaden)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lbURL)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(12, 12, 12)
                .addComponent(lbETA)
                .addGap(5, 5, 5)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbDownloadnaar)
                    .addComponent(lbDownloadLocation))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lbOverdrachtsnelheid)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 134, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btStart)
                    .addComponent(btOpenFolder))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btOpenFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btOpenFolderActionPerformed
        try {
            Desktop.getDesktop().open(temp.getParentFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_btOpenFolderActionPerformed

    /**
     * Hierin definieren we de Swingworker en downloaden we het opgegeven bestand.
     * Tijdens de download wordt de progressbar gevuld.
     * Er zijn 3 verschillende download fases: READY, DOWNLOADING en DONE en 
     * aan de hand van de fase wordt een bepaalde actie uitgevoerd.
     * @param evt 
     */
    private void btStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btStartActionPerformed
        SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {

            private int fileSize = 0;

            @Override
            protected Integer doInBackground() throws Exception {
                BufferedOutputStream outputStream = null;
                URLConnection connection = null;
                try {
                    URL newurl = new URL(url);
                    connection = newurl.openConnection();
                    // Buffered streams zijn sneller, maar je kunt ze
                    // vervangen door normale input en output streams.
                    BufferedInputStream inputStream = new BufferedInputStream(
                            connection.getInputStream());
                    outputStream = new BufferedOutputStream(
                            new FileOutputStream(temp));

                    fileSize = connection.getContentLength();
                    int downloadedSize = 0;
                    System.out.println("Filesize:" + fileSize);
                    while (true) {   
                        int b = inputStream.read();
                        if (b == -1 || Thread.interrupted()) {
                            break; // -1 betekent end-of-stream, stoppen
                        }
                        outputStream.write(b);
                        downloadedSize++;
                        publish(downloadedSize);
                    }
                } catch (IOException ex) {
                    System.err.println("Probleem met downloaden van bestand.");
                    ex.printStackTrace(System.err);
                } finally { // Altijd de streams sluiten
                    try {
                        if (outputStream != null) {
                            outputStream.close();
                        }
                    } catch (IOException ex) { /*
                         * deze kunnen we negeren
                         */ }
                    try {
                        if (connection != null) {
                            connection.getInputStream().close();
                        }
                    } catch (IOException ex) { /*
                         * deze kunnen we negeren
                         */ }
                }
                return 100;
            }

            @Override
            protected void process(List<Integer> downloadedBytes) {
                progressBar.setMaximum(fileSize);
                progressBar.setValue(downloadedBytes.get(downloadedBytes.size() - 1));
            }

            @Override
            protected void done() {
                btStart.setEnabled(false);
                btOpenFolder.setEnabled(true);
                currentDownloadState = downloadState.DONE;
            }
        };
        
        switch (currentDownloadState) {
            case READY:
                worker.execute();
                btStart.setText("Annuleren");
                currentDownloadState = downloadState.DOWNLOADING;
                break;
            case DOWNLOADING:
                worker.cancel(true);
                currentDownloadState = downloadState.DONE;
                break;
            case DONE:
                
                break;
        }
    }//GEN-LAST:event_btStartActionPerformed

    /**
     * 
     * @param url de URL naar het bestand dat je wilt downloaden 
     */
    private void setURL(String url) {
        this.url = url;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MainJFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btOpenFolder;
    private javax.swing.JButton btStart;
    private javax.swing.JLabel lbBezigMetDownloaden;
    private javax.swing.JLabel lbDownloadLocation;
    private javax.swing.JLabel lbDownloadnaar;
    private javax.swing.JLabel lbETA;
    private javax.swing.JLabel lbOverdrachtsnelheid;
    private javax.swing.JLabel lbURL;
    private javax.swing.JProgressBar progressBar;
    // End of variables declaration//GEN-END:variables
}
